<%@ WebHandler Language="C#" Class="TreeHandler" %>

using System;
using System.Web;
using GridControl;//to use the TreeNode class
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data.SqlClient;
using System.Data;
public class TreeHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        List<GridControl.TreeNode> nodes = new List<GridControl.TreeNode>();
        SqlConnection con = new SqlConnection();
        con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection= con;
        cmd.CommandText = "Select * from tb_tree where id_parent=@id_parent";
        cmd.Parameters.AddWithValue("@id_parent",context.Request["node"]);
        SqlDataAdapter adapt = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adapt.Fill(ds);
        con.Close();
        con.Dispose();
        cmd.Dispose();
        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
        {
            
            GridControl.TreeNode no = new GridControl.TreeNode();
            no.draggable = true;
            no.id = ds.Tables[0].Rows[i]["id"].ToString();
            no.text = ds.Tables[0].Rows[i]["text"].ToString();
            no.leaf = !HasChildren(ds.Tables[0].Rows[i]["id"].ToString());//see if the node has children
            no.parentNodeId = context.Request["node"];
            nodes.Add(no);
        }
        JavaScriptSerializer ser = new JavaScriptSerializer();
        context.Response.Write(ser.Serialize(nodes));
    }
    private  bool HasChildren(string idNode){
        SqlConnection con = new SqlConnection();
        con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Select * from tb_tree where id_parent=@id_parent";
        cmd.Parameters.AddWithValue("@id_parent", idNode);
        SqlDataReader reader = cmd.ExecuteReader();
        bool hasChildren = false;
        if (reader.Read())
        {
            hasChildren = true;
        }
        reader.Close();
        con.Close();
        con.Dispose();
        cmd.Dispose();
        return hasChildren;
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

}